package com.wwz.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wwz.pojo.Personnel;
import com.wwz.pojo.User;
import com.wwz.pojo.model.LoginModel;
import com.wwz.pojo.query.PersonnelQuery;
import com.wwz.pojo.query.UserQuery;
import com.wwz.service.IUserService;
import com.wwz.util.EcoBootException;
import com.wwz.util.JobUtils;
import com.wwz.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户控制层
 * @date 2022/04/08 28:08:24
 */
@RestController
@RequestMapping("/manage/user")
@Api(tags = "用户控制层")
public class UserController {

    @Resource
    private IUserService userService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginModel loginModel){
        JobUtils.checkLoginModel(loginModel);
        LoginModel login = userService.login(loginModel);
        if (login != null ){
            return Result.ok("ok",login);
        }
        return Result.error("用户名密码错误");
    }


    @ApiOperation("退出登录")
    @PostMapping("/loginOut")
    public Result loginOut( ){
        StpUtil.logout();
        return Result.ok();
    }

    @ApiOperation("用户列表")
    @GetMapping("/toPage")
    public Result toPage(UserQuery query){
        IPage<User> iPage = userService.toPage(query);
        return Result.ok(iPage);
    }

    @ApiOperation("获取所有用户")
    @GetMapping("/getUsers")
    public Result toPage(){
        List<User> users = userService.list();
        return Result.ok(users);
    }

    @ApiOperation("添加或修改")
    @PostMapping("/addOrUpdate")
    public Result addOrUpdate(@RequestBody User user){
        if (StrUtil.isAllEmpty(user.getUserName(),user.getPassWord())){
            throw new EcoBootException("信息不能为空");
        }
        userService.addOrUpdate(user);
        return Result.ok("ok");
    }

    @ApiOperation("删除")
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable String id){
        if (StrUtil.isEmpty(id)){
            throw new EcoBootException("id不能为空");
        }
        userService.removeById(id);
        return Result.ok("ok");
    }

    @ApiOperation("禁用")
    @GetMapping("/isAble/{id}")
    public Result isAble(@PathVariable String id){
        if (StrUtil.isEmpty(id)){
            throw new EcoBootException("id不能为空");
        }
        User user = userService.getById(id);
        switch (user.getStatus()){
            case 0:user.setStatus(1);
            break;
            case 1:user.setStatus(0);
            break;
        }
        userService.updateById(user);
        return Result.ok();
    }

}
